/****************************************************************************
 * ttext: Teradata Tools & Extensions
 * -------------------------------------------------------------------------
 * "C" User-Defined Function:  SECONDS(DS)
 *
 * Description
 * -----------
 * A simple function that converts an interval (DAY(2) TO SECOND(2)) into an
 * DECIMAL(9,2) number of seconds.
 *
 * Interval values are most commonly generated as the difference of two
 * timestamps:
 *
 *   SELECT
 *     AVG(SECONDS(FirstRespTime - StartTime DAY TO SECOND))
 * 
 * Teradata does not automatically convert HOUR TO SECOND, MINUTE TO SECOND,
 * HOUR TO MINUTE, etc. to the DAY TO SECOND interval type.  Additional UDFs
 * are required to support these types.
 * 
 * Contributors
 * ------------
 * 2007-12-15  /  trojancjs (Chris Stephens)  /  Yorba Linda, CA - USA
 * - Initial Development.
 *
 * ==== Please do not add comments about code change history.  This     ====
 * ==== information belongs in source control comments, not the source  ====
 * ==== code file.  Thanks!                                             ====
 ****************************************************************************/
#include "ttext_lib.h"

/*********************************
 * Teradata User Defined Function
 *********************************/

void ttext_udf_seconds_DS(
  IntrvlDtoS    *interval  /* DAY TO SECONDS(2) */
, DECIMAL4      *result    /* DECIMAL(9,2) */
, BOOLEAN       *intervalIsNull
, BOOLEAN       *resultIsNull
, char           sqlstate[6]
, SQL_TEXT       function_name[129]
, SQL_TEXT       specific_function_name[129]
, SQL_TEXT       error_message[257]
)
{
  /* by default, return success */
  TTEXT_set_error_message("00000", "");

  if (*intervalIsNull)
  {
    *resultIsNull = TRUE;
  }
  else
  {
    /* "seconds" received as a DECIMAL(8,6), regardless of the INTERVAL
     * SECONDS(n) scale.  Seconds value must be scaled back by 4 digits,
     * while other values must be scaled up by 2 digits.
     */
    *result = (interval->seconds / 10000) +
               interval->minute * 60 * 100 +
               interval->hour * 60 * 60 * 100 +
               interval->day * 24 * 60 * 60 * 100;
  }

  return;
}
